package cn.lbz.Food.Init;

import cn.lbz.Food.Init.DBfood;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtils {
    private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String DB_URL    = "jdbc:mysql://127.0.0.1:3306/food";
    private static final String DB_USER   = "root";
    private static final String DB_PASS   = "20020111Zhao";

    public static void insert(String sql) throws SQLException {
        excute(sql);
    }
    public static void delete(String sql) throws SQLException {
        excute(sql);
    }

    public static void update(String sql) throws SQLException {
        excute(sql);
    }

    private static void excute(String sql) throws SQLException {
        try {
            Class.forName(DB_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS)) {
            try (Statement statement = connection.createStatement()) {
                statement.execute(sql);
            }
        }
    }

    public static List<DBfood> getfood(String sql) throws SQLException {
        try {
            Class.forName(DB_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        List<DBfood> food = new ArrayList<>();

        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS)) {
            try (Statement statement = connection.createStatement()) {
                ResultSet rs = statement.executeQuery(sql);
                while (rs.next()) {
                    DBfood Food = new DBfood();
                    Food.setId(rs.getInt("id"));
                    Food.setName(rs.getString("name"));
                    Food.setLocated(rs.getString("located"));
                    Food.setType(rs.getString("type"));
                    Food.setPrice(rs.getInt("price"));
                    Food.setreason(rs.getString("reason"));
                    Food.setPics(rs.getString("pics"));
                    food.add(Food);
                }
            }
        }
        return food;
    }
}
